<template>
	<view>
		<input type="text" placeholder="请输入内容" v-model="value" />
		<button @click="handleSubmit">发送</button>
		
		<view class="" v-for="(item, index) in list" :key="index">{{item.message}}</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	const value = ref('')
	const list = ref([])
	// 1. 建立链接
	const socketTask = uni.connectSocket({
		url: 'ws://124.221.74.149:8003/koa/ws?user_id=1&server_id=2'
	})


	// 2。打开链接 获取聊天记录
	uni.onSocketOpen(() => {
		console.log('ws 服务器已经打开， 开始获取聊天列表数据');
		getChatList()
	})


	// 5. 发送消息
	const handleSubmit = () => {
		
		uni.sendSocketMessage({
			data: JSON.stringify({
				type: 'addMessage',
				data: {
					user_id: 1,
					server_id: 2,
					message: value.value,
					type: 'text'
				}
			})
		})
	}

	// 3. 监听， 消息
	uni.onSocketMessage((resp) => {
		const data = JSON.parse(resp.data)
		console.log(data)
		if(data.type === 'getChatList') {
			list.value = data.data;
		}
	})


	// 4. 获取聊天记录
	const getChatList = () => {
		uni.sendSocketMessage({
			data: JSON.stringify({
				type: 'getChatList'
			})
		})
	}
</script>

<style lang="scss">

</style>